package demo;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class Demo {
    public static void main(String[] args) throws InstantiationException, NoSuchFieldException, IllegalAccessException {
        // 无法直接实例化 单例 对象 ，可通过Unsafe类来实现 单例Bean的实例化
        // Singleton singleton = new Singleton();
        Singleton instance =(Singleton)MyUtils.getUnSafe().allocateInstance(Singleton.class);
        Field age = Singleton.class.getDeclaredField("age");

        long l = MyUtils.getUnSafe().objectFieldOffset(age);
//        MyUtils.getUnSafe().putInt(instance,l,13);
        MyUtils.getUnSafe().setMemory(instance,l,1L,(byte) 1);
//        age.setAccessible(true);
//        age.set(instance,123);


        System.out.println(instance.toString());
    }
}

class Singleton{

    private static final Singleton SINGLETON = new Singleton(1,"23");

    private final int age;
    private final String name;

    private Singleton(int age, String name) {
        this.age = age;
        this.name = name;
    }

    private Singleton getSingleton(){
        return SINGLETON;
    }

    @Override
    public String toString() {
        return "Singleton{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
